/**
 * 
 */
package com.p2p.backend.interceptors;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.p2p.base.interceptors.BaseLoginInterceptor;
import com.p2p.base.util.LoginUtil;

/**
 * @author ruiqi
 *
 */
public class BackendLoginInterceptor extends BaseLoginInterceptor{

	String index = "/tpl/index/index.html";
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		LoginUtil.setCurrentUser(null);
		initCurrentUser(request, response);
		if(LoginUtil.getCurrentUser()!=null){
			return true;
		}else{
			
			String uri =request.getRequestURI();
			
			if(StringUtils.isNotBlank(uri)&&uri.endsWith(index)){
			/*if(StringUtils.isNotBlank(uri)&&uri.contains(".html")){*/
				response.sendRedirect(loginCenterUrl + "?backUrl=" + loginBackUrl);
			}else{
				doLoginNeed(response);
			}
			
			return false;
		}
		
	}
	
	protected void doLoginNeed(HttpServletResponse response){
		response.setContentType("application/json");
		PrintWriter pWriter = null;
		try {
			pWriter = response.getWriter();
			JSONObject jobject = new JSONObject();
			jobject.put("res", -1);
			jobject.put("url", loginCenterUrl + "?backUrl=" + loginBackUrl);
			pWriter.write(jobject.toJSONString());
		} catch (IOException e) {
			logger.error("", e);
		} finally {
			if (pWriter != null) {
				pWriter.flush();
				pWriter.close();
			}
		}
}
}
